package com.jinit.jia.boot.web.embedded.tomcat;

import com.jinit.jia.boot.web.server.WebServer;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.springframework.util.Assert;

/**
 * TomcatWebServer
 *
 * @author JInit
 * @date 2021-08-06
 */
public class TomcatWebServer implements WebServer {

    private final Tomcat tomcat;

    private final boolean autoStart;

    private final Object monitor = new Object();

    public TomcatWebServer(Tomcat tomcat) {
        this(tomcat, true);
    }

    public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
        Assert.notNull(tomcat, "Tomcat 服务不能为空");
        this.tomcat = tomcat;
        this.autoStart = autoStart;
        initialize();
    }
    private void initialize() {
        try {
            this.tomcat.start();
            startDaemonAwaitThread();
        } catch (LifecycleException e) {
            e.printStackTrace();
            throw new RuntimeException("Tomcat启动异常",e);
        }
    }

    private void startDaemonAwaitThread() {
        Thread awaitThread = new Thread("container-" + this) {

            @Override
            public void run() {
                TomcatWebServer.this.tomcat.getServer().await();
            }

        };
        awaitThread.setContextClassLoader(getClass().getClassLoader());
        awaitThread.setDaemon(false);
        awaitThread.start();
    }

    @Override
    public void start() throws Exception {
        synchronized (this.monitor) {
            this.tomcat.start();
        }
    }

    @Override
    public void stop() throws Exception {
        synchronized (this.monitor) {
            this.tomcat.stop();
        }
    }

    @Override
    public int getPort() {
        Connector connector = this.tomcat.getConnector();
        if (connector != null) {
            return connector.getLocalPort();
        }
        return 0;
    }
}
